package videoCapture;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import javax.imageio.ImageIO;

public class UdpServer {
	public static final int PORT = 5000;
    private DatagramSocket dataSocket;
    private DatagramPacket dataPacket;
    private byte receiveByte[];
    private String receiveStr;

    public UdpServer() {
        Init();
    }

    public void Init() {
        try {
            dataSocket = new DatagramSocket(PORT);
            receiveByte = new byte[1024];
            dataPacket = new DatagramPacket(receiveByte, receiveByte.length);
 //           receiveStr = "";
            int i = 0;
            ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
            BufferedImage image;
            int bufSize = 0;
            while (i == 0 )// 无数据，则循环
            {
                dataSocket.receive(dataPacket);
                i = dataPacket.getLength();
                bufSize += i;
                // 接收数据
                System.out.println("server "+i);
                if (i > 0) {
                    // 指定接收到数据的长度,可使接收数据正常显示,开始时很容易忽略这一点
                	
 //                   receiveStr = new String(receiveByte, 0, dataPacket.getLength());
 //                   System.out.println(receiveStr);
                	bout.write(dataPacket.getData(),0,i);
                    i = 0;// 循环接收
                    continue;
                }
                break;
            }
            System.out.println("server "+bufSize);
            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());  
            image = ImageIO.read(bin);
            ImageIO.write(image, "jpg", new File("output.jpg"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        new UdpServer();
    }
}
